package cn.shiva.redisunit.message.list;

import cn.shiva.redisunit.message.MessageBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis list 实现消息队列
 *
 * @author shiva   2022-08-14 0:06
 */
@Component
public class MessageListComponent {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 左侧消息入队
     */
    public void leftPush(String key, MessageBO message) {
        redisTemplate.opsForList().leftPush(key, message);
    }

    /**
     * 右侧消息出队；
     * 1.最长阻塞时间为5分钟，到达时间或者获取到消息，就会立刻结束监听
     * 2.所以在redis关闭连接、或者消息返回后，要重新开启监听
     */
    public MessageBO rightPop(String key) {
        return (MessageBO) redisTemplate.opsForList().rightPop(key, 5, TimeUnit.MINUTES);
    }

}
